package pkg

import (
	"context"
	"errors"
	"github.com/redis/go-redis/v9"
	"strconv"
	"time"
	"user_bff/global"
)

// 短信限制器
func SendSmsLimit(mobile string) error {
	key := mobile + "send_sms_limit"
	now := time.Now()
	BeforeHourTime := strconv.FormatInt(time.Now().Add(-1*time.Hour).Unix(), 10)
	result, err := global.RedisClient.ZCount(context.Background(), key, BeforeHourTime, strconv.FormatInt(now.Unix(), 10)).Result()
	if err != nil {
		return err
	}
	if result >= 3 {
		return errors.New("一小时内只能发三次")
	}
	_, err = global.RedisClient.ZAdd(context.Background(), key, redis.Z{
		Score:  float64(time.Now().Unix()),
		Member: time.Now().Unix(),
	}).Result()
	if err != nil {
		return err
	}
	return nil
}

// redis存储短信验证码
func SetSendSms(mobile string, code string) error {
	err := global.RedisClient.Set(context.Background(), "SendSms"+mobile, code, 3*time.Minute).Err()
	if err != nil {
		return errors.New("redis存储失败")
	}
	return nil
}

// redis获取短信验证码
func GetSendSms(mobile string) (string, error) {
	result, err := global.RedisClient.Get(context.Background(), "SendSms"+mobile).Result()
	if err != nil {
		return "", errors.New("redis获取失败")
	}
	return result, nil
}
